package hoowin.app.cadc.dao.springImp;

import java.sql.ResultSet;
import java.sql.SQLException;

import hoowin.app.cadc.dao.ICadcUserDao;
import hoowin.app.cadc.model.CadcUser;
import hoowin.app.cadc.model.Entrant;
import hoowin.common.model.FileItem;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class CadcUserDao extends JdbcDaoSupport implements ICadcUserDao {

	@Override
	public CadcUser getBasicInfo(int id) {
		String sql = "select * from apps_cadc_users where user="+id;
		return (CadcUser)super.getJdbcTemplate().queryForObject(sql, new CadcUserRowMapper());
	}

	@Override
	public boolean updateBasicInfo(CadcUser cadcUser) {
		String sql="update apps_cadc_users set work_name=?, work_type=?, society=?, remark=?, status=?, secondMem=?, thirdMem=?, teacher=? where apps_cadc_users.id=?";
		if(super.getJdbcTemplate().update(sql, cadcUser.getWorkName(), cadcUser.getWorkType(), cadcUser.getSociety(), cadcUser.getRemark(), cadcUser.getStatus(), cadcUser.getSecondMem().getId(), cadcUser.getThirdMem().getId(), cadcUser.getTeacher().getId(), cadcUser.getId())>0){
			return true;
		}else return false;
	}

	@Override
	public boolean updateWork(int workId, int userId) {
		String sql="update apps_cadc_users set status=3, work="+workId+" where user="+userId;
		if(super.getJdbcTemplate().update(sql)>0){
			return true;
		}else return false;
	}

	@Override
	public int createAccount(int userId, String number, String college) {
		String sql = "insert into apps_cadc_users (id, user, number, college) values (null, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, userId, number, college )>0){
			return super.getJdbcTemplate().queryForInt("select last_insert_id()");
		}else return 0;
	}
	
	class CadcUserRowMapper implements RowMapper<Object>{
		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			CadcUser user = new CadcUser();
			user.setId(rs.getInt("id"));
			Entrant en1 = new Entrant();
			en1.setId(rs.getInt("user"));
			en1.setCollege(rs.getString("college"));
			en1.setNumber(rs.getString("number"));
			user.setFirstMem(en1);
			Entrant en2 = new Entrant();
			en2.setId(rs.getInt("secondMem"));
			user.setSecondMem(en2);
			Entrant en3 = new Entrant();
			en3.setId(rs.getInt("thirdMem"));
			user.setThirdMem(en3);
			Entrant en4 = new Entrant();
			en4.setId(rs.getInt("teacher"));
			user.setTeacher(en4);
			FileItem fi = new FileItem();
			fi.setId(rs.getInt("work"));
			user.setWork(fi);
			user.setRemark(rs.getString("remark"));
			user.setSociety(rs.getString("society"));
			user.setWorkName(rs.getString("work_name"));
			user.setWorkType(rs.getInt("work_type"));
			user.setStatus(rs.getInt("status"));
			return user;
		}	
	}
}
